package org.dlust.context;

import org.dlust.beans.BeanDefinition;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassPathXmlApplicationContext {
  private final List<BeanDefinition> beanDefinitions = new ArrayList<>();
  private final Map<String, Object> singletons = new HashMap<>();

  public ClassPathXmlApplicationContext(String fileName) throws ClassNotFoundException, DocumentException {
    this.readXml(fileName);
    this.instanceBeans();
  }

  private void readXml(String fileName) throws DocumentException {
    SAXReader saxReader = new SAXReader();

    try {
      URL xmlPath = this.getClass().getClassLoader().getResource(fileName);

      Document document = saxReader.read(xmlPath);
      Element rootElement = document.getRootElement();
      for (Element element : (List<Element>) rootElement.elements()) {
        String beanID = element.attributeValue("id");
        String beanClassName = element.attributeValue("class");
        BeanDefinition beanDefinition = new BeanDefinition(beanID, beanClassName);
        beanDefinitions.add(beanDefinition);
      }
    } catch (DocumentException e) {
      System.out.println(e.getMessage());
    }
  }

  private void instanceBeans() throws ClassNotFoundException {
    for (BeanDefinition beanDefinition : beanDefinitions) {
      try {
        singletons.put(beanDefinition.getId(),
            Class.forName(beanDefinition.getClassName()).newInstance());
      } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
      }
    }
  }

  public Object getBean(String beanName) {
    return singletons.get(beanName);
  }
}
